<template>
  <div>
    <div class="sub-title-bg flex-row justify-between align-center">
      <span class="sub-title">清理数量</span>
      <div class="sub-right flex-row justify-around">
        <div class="sub-right-item"
             :class="{'active':active==item.value}"
             v-for="(item,index) in items"
             :key="index"
             @click="handleActive(item)">
          {{item.name}}
        </div>
      </div>
    </div>
    <div class="container flex-row align-center flex-wrap">

      <div class="item flex-row align-center">
        <img src="@/assets/images/item-1.png" />
        <div class="item-right">
          <div class="item-num">
            <span class="item-num-text color-2">{{num[0]}}</span>
            <span class="item-unit">个</span>
          </div>
          <div class="item-name">吸污处理</div>
        </div>
      </div>

      <div class="item flex-row align-center">
        <img src="@/assets/images/item-2.png" />
        <div class="item-right">
          <div class="item-num">
            <span class="item-num-text color-1">{{num[1]}}</span>
            <span class="item-unit">个</span>
          </div>
          <div class="item-name">普通清理</div>
        </div>
      </div>

      <div class="item flex-row align-center">
        <img src="@/assets/images/item-3.png" />
        <div class="item-right">
          <div class="item-num">
            <span class="item-num-text color-3">{{num[2]}}</span>
            <span class="item-unit">吨</span>
          </div>
          <div class="item-name">易腐垃圾</div>
        </div>
      </div>

    </div>

    <div id="chart"
         class="chart-view"
         ref="chart">

    </div>
  </div>
</template>

<script>
import { apiGetCleanNumber, apiGetCleaningQuantityList } from '@/api/api'
let chart = null;
import * as echarts from 'echarts'
export default {
  data () {
    return {
      active: 'day',
      items: [{ name: '今日', value: 'day' }, { name: '本月', value: "month" }, { name: '本年', value: 'year' }],
      num: [0, 0, 0],
      chartOptions: {

      },
      month: 1,
      dataList: []
    }
  },
  beforeDestroy () {
    if (chart) {
      chart.clear();
    }
  },
  destroyed () {
    if (chart) {
      chart.dispose();
    }
  },
  mounted () {
    let date = new Date();
    this.month = date.getMonth() + 1;
    // this.initChart();
    // this.updateChart();

    this.getData();
    this.getChartData();

  },
  methods: {
    getData () {
      apiGetCleanNumber({ type: this.active }).then(res => {
        if (res.code == 1) {
          let data = [res.data.suctionCleaning, res.data.normalCleaning, res.data.perishableGarbageWeight]
          this.num = [...data];
        }
      })
    },
    getChartData () {
      apiGetCleaningQuantityList().then((res) => {
        if (res.code == 1) {
          this.dataList = res.data;
        }
      }).finally(() => {
        this.initChart();
      })
    },
    handleActive (item) {
      if (this.active != item.value) {
        this.active = item.value;
        this.getData();
        // this.updateChart()
      }
    },
    initChart () {
      // 初始化option
      let xAxisData = Object.keys(this.dataList);
      let yData = Object.values(this.dataList);
      let maxValue = 0;
      yData.forEach((item)=>{
        let val = parseFloat(item);
        if(val > maxValue){
          maxValue = val;
        }
      })

      if(maxValue <1){
        maxValue = 100; 
      } 

      //最大
      let maxDataList = [];
      xAxisData.forEach((item)=>{
        maxDataList.push(maxValue);
      })

      //当天
      let currentDataList = [];
      xAxisData.forEach((item,index)=>{
        if(index == xAxisData.length -1){
          currentDataList.push({
            value:yData[index-1],
              itemStyle: {
                  // 线性渐变，前四个参数分别是 x0, y0, x2, y2, 范围从 0 - 1，分别表示右,下,左,上。例如（0，0，0，1）表示从正上开始向下渐变；如果是（1，0，0，0），则是从正右开始向左渐变。
                  // 相当于在图形包围盒中的百分比，如果最后一个参数传 true，则该四个值是绝对的像素位置
                  color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [{
                    offset: 0,
                    color: '#F3B600' //指0%处的颜色
                  }, {
                    offset: 1,
                    color: '#71D300' //指100%处的颜色
                  }])
                }
          });
        }
        else {
          currentDataList.push(0)
        }
      })

      //其他天
      if(yData.length > 0){
        yData[yData.length -1] = 0
      }

      var _this = this;
      const initOptions = {
        // 坐标轴位置
        grid: {
          top: '12%',
          left: '5%',
          right: '30',
          bottom: '2%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',

          // 添加 $ 前缀
          valueFormatter: (value) => {
            return value + '吨'
          },
          // 添加 $ 前缀

          // 提示框浮层内容格式器: 自定义提示框样式
          formatter: function (params) { // params 是 formatter 需要的数据集
            // console.log('params', params)
            let content = "";

            //0 最大值 1 其他月份  2 当前值
            if (params[0].axisValue == _this.month) {
              content += `<div style="height: 25px; line-height: 25px;">
                      <!-- 圆点样式 -->
                      <span style="display: inline-block; margin-right: 10px; border-radius: 50%; width: 8px; height: 8px;background-color: ${params[2].color};"></span>
                      <span style="color: #424864;">${params[2].seriesName}:</span>
                      <span style="color: #172045;">${params[2].value} 吨</span>
                    </div>`;
            }
            else {
              content += `<div style="height: 25px; line-height: 25px;">
                      <!-- 圆点样式 -->
                      <span style="display: inline-block; margin-right: 10px; border-radius: 50%; width: 8px; height: 8px;background-color: ${params[1].color};"></span>
                      <span style="color: #424864;">${params[1].seriesName}:</span>
                      <span style="color: #172045;">${params[1].value} 吨</span>
                    </div>`;
            }

            let unit = '日'
            // if (_this.active == 1) {
            //   unit = '月'
            // }
            // else if (_this.active == 2) {
            //   unit = '年'
            // }

            // 提示框外框样式及内容数据
            const htmlContent = `<div style="width: 180px; height: 65px;">
            <!-- 提示框顶部标题样式及数据 smsUseData.xAxis.date（标题数据）-->
            <div style="color: #000000D9; border-bottom: 1px solid #F0F0F0; padding: 5px 16px;">
                ${params[0].axisValueLabel}${unit}
            </div>
            <div style="padding: 12px 16px; position: relative;">
              ${content}
            </div>
          </div>`;

            return htmlContent;
          },
        },
        legend: {
          show: true,
          right: '2%',
          itemWidth: 7,
          itemHeight: 7,
          data: ['易腐垃圾', '今日易腐垃圾'],
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          show: true,
          type: 'category',
          name: "日",
          nameTextStyle: {
            color: "#fff"
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          },
          data: xAxisData
        },
        yAxis: {
          type: 'value',
          name: "单位:吨",
          nameLocation: "middle",
          nameTextStyle: {
            color: '#fff'
          },
          axisLabel: {
            color: '#fff'
          },
          nameGap: 30,
          splitNumber: 3,
          nameRotate: -90,
          splitLine: {
            // 网格线
            show: true,
            lineStyle: { //分割线
              color: "#30436D",
              width: 1,
              type: "dashed" //dotted：虚线 solid:实线
            }
          },
          max: function (value) {
            return value.max;
          }
        },
        series: [
          {
            // name: "今日废弃油脂",
            data: maxDataList,
            type: 'bar',
            barWidth: 18,
            itemStyle: {
              color: 'rgba(88, 184, 252, 0.1)'
            },
            barGap: '-78%',
          },
          {
            name: "易腐垃圾",
            data: yData,
            type: 'bar',
            barWidth: 8,
            // showBackground: true,
            // backgroundStyle: {
            //   color: 'rgba(88, 184, 252, 0.1)'
            // }
          },
          {
            name: "今日易腐垃圾",
            // data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            //   {
            //     value: 100,
            //     itemStyle: {
            //       // 线性渐变，前四个参数分别是 x0, y0, x2, y2, 范围从 0 - 1，分别表示右,下,左,上。例如（0，0，0，1）表示从正上开始向下渐变；如果是（1，0，0，0），则是从正右开始向左渐变。
            //       // 相当于在图形包围盒中的百分比，如果最后一个参数传 true，则该四个值是绝对的像素位置
            //       color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [{
            //         offset: 0,
            //         color: '#F3B600' //指0%处的颜色
            //       }, {
            //         offset: 1,
            //         color: '#71D300' //指100%处的颜色
            //       }])
            //     }
            //   },],
            data:currentDataList,
            type: 'bar',
            barWidth: 8,
            // showBackground: true,
            // backgroundStyle: {
            //   color: 'rgba(88, 184, 252, 0.1)'
            // }
          },
        ]
      }

      chart = echarts.init(this.$refs.chart)
      chart.setOption(initOptions)

      window.addEventListener("resize", function () {
        chart.resize();
      });
    },
    updateChart () {
      let option = {
        xAxis: {

        },
        legend: {

        },
        series: [
          {

          },
          {

          },
          {

          }
        ]
      }
      if (this.active == 2) {
        option.xAxis.name = "年"
        option.legend.data = ['易腐垃圾', '今年易腐垃圾']
        option.series[2].name = "今年易腐垃圾"
      }
      else if (this.active == 1) {
        option.xAxis.name = "月",
          option.legend.data = ['易腐垃圾', '当月易腐垃圾']
        option.series[2].name = "当月易腐垃圾"
      }
      else {
        option.xAxis.name = "日"
        option.legend.data = ['易腐垃圾', '今日易腐垃圾']
        option.series[2].name = "今日易腐垃圾"
      }
      chart.setOption(option)
    },
  }
}
</script>

<style lang="scss" scoped>
.sub-title-bg {
  background: url('@/assets/images/title-l.png') no-repeat;
  background-size: 100% 100%;
  width: 439px;
  height: 39px;

  .sub-title {
    margin-left: 35px;
    font-size: 30px;
    font-family: YouSheBiaoTiHei;
    font-weight: normal;
    color: #f8f8f8;
    line-height: 42px;
    margin-bottom: 5px;
  }

  .sub-right {
    margin-bottom: 5px;
    .sub-right-item {
      width: 54px;
      margin-left: 10px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.7);
      cursor: pointer;
      &.active {
        background: url('@/assets/images/item-active.png') no-repeat;
        background-size: 100% 100%;

        color: #fff;
      }
    }
  }
}

.container {
  margin-top: 2px;
  width: 439px;
  padding: 8px;
  .item {
    margin-top: 15px;
    margin-right: 60px;

    &:last-child {
      margin-right: 0;
    }
    img {
      width: 48px;
      height: 48px;
    }
    .item-right {
      margin-left: 8px;

      .color-1 {
        color: #69c0ff;
      }

      .color-2 {
        color: #ffc53d;
      }

      .color-3 {
        color: #6be6de;
      }

      .item-num {
        .item-num-text {
          font-size: 32px;
          font-family: PangMenZhengDaoBiaoTiTiMianFeiBan,
            PangMenZhengDaoBiaoTiTiMianFeiBan;
          font-weight: normal;

          line-height: 40px;
        }

        .item-unit {
          margin-left: 4px;
          font-size: 14px;
          font-weight: 400;
          color: #b6d9fc;
          line-height: 20px;
        }
      }

      .item-name {
        font-size: 14px;
        font-weight: 400;
        color: #b6d9fc;
        line-height: 24px;
      }
    }
  }
}

.chart-view {
  width: 400px;
  height: 180px;
}
</style>